package com.zk.yygh.order.api;

import com.zk.yygh.enums.PaymentTypeEnum;
import com.zk.yygh.hosp.result.Result;
import com.zk.yygh.order.service.OrderService;
import com.zk.yygh.order.service.PaymentService;
import com.zk.yygh.order.service.WeiXinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 *
 * @author: 张凯
 * @date: 2022/6/22 - 17:24
 */
@Api(tags = "微信支付相关")
@RestController
@RequestMapping("/api/order/weixin")
public class WeiXinController {

    @Autowired
    private WeiXinService weiXinService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private OrderService orderService;

    @ApiOperation("下单生成微信支付二维码链接")
    @GetMapping("createNative/{orderId}")
    public Result createNative(@PathVariable("orderId") Long orderId){
        //获取生成二维码的相关参数
        Map<String, Object> nativeParam = weiXinService.createNative(orderId);
        return Result.ok(nativeParam);
    }

    @ApiOperation("查询支付状态")
    @GetMapping("queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable("orderId") Long orderId){
        //1.查询订单支付结果：TODO:当前只限微信支付
        Map<String,String> restMap=paymentService.queryPayStatus(orderId);
        //2.结果为空为支付失败
        if (restMap==null||"FAIL".equals(restMap.get("trade_state"))){
            return Result.fail().message("支付出错");
        }
        //3.结果为SUCCESS为支付成功
        if ("SUCCESS".equals(restMap.get("trade_state"))){
            //3.1 获取商户订单号
            String outTradeNo = restMap.get("out_trade_no");
            //3.2 调用支付业务执行更新订单表及支付表
            paymentService.paySuccess(outTradeNo, PaymentTypeEnum.WEIXIN.getStatus(), restMap);
            System.out.println("支付成功...");
            return Result.ok().message("支付成功");
        }
        //4.其他结果为正在支付
        return Result.ok().message("支付中");
    }

    @ApiOperation("取消订单")
    @GetMapping("auth/cancelOrder/{orderId}")
    public Result cancelOrder(@PathVariable("orderId") Long orderId){
        boolean isCancel = orderService.cancelOrder(orderId);
        return Result.ok(isCancel);
    }

}
